package com.sdjenkins.exercise.atm;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.Reader;
import java.io.Writer;
import java.util.Observable;

/**
 * This represents the View part of the application and so provides Input and Output 
 * for the ATM Application.
 * 
 * Will currently allow any input/output that can be defined by a 
 * java.io.Reader or java.io.Writer class.
 * 
 * It uses the Observer pattern to send input events to a controller 
 * 
 * 
 * @author Simon Jenkins
 *
 */
public class ATMInputOutput extends Observable {
	
	Writer out;
	Reader in;
	BufferedReader bReader;
	BufferedWriter bWriter;
	
	public void start() {
		
		bReader = new BufferedReader(in);
		bWriter = new BufferedWriter(out);
		String line;
		while ((line = readNext()) != null) {
			setChanged();
			notifyObservers(line);
		}
		try {
			bReader.close();
			bWriter.close();
		}
		catch (Exception e) {
			handleException(e);
		}
		notifyObservers(null);
	}
	
	private String readNext() {
		String line = null;
		try {
			line = bReader.readLine();
		}
		catch (Exception e) {
			handleException(e);
		}
		return line;
	}

	public void setReader(Reader rdr) {
		in = rdr;		
	}
	public void setWriter(Writer wr) {
		out = wr;
	}
	
	
	public void output(String output) {
		if (output != null) {
			try {
				bWriter.write(output+"\n");
			}
			catch (Exception e) {
				handleException(e);
			}
		}
	}
	
	private void handleException(Exception e) {
		throw new RuntimeException(e);		
	}

}
